using UnityEngine;
using System.Collections;


public class PlayerControl : MonoBehaviour
{
    public Texture Textura;

    Texture BackupTextura = null;
    bool DefaultTexture = false;
    public void ChangeFicha(ref Material FichaBoard)
    {
        if (DefaultTexture)
        {
            FichaBoard.mainTexture = BackupTextura;
        }
        else
        {
            BackupTextura = FichaBoard.mainTexture;
            FichaBoard.mainTexture = Textura;
        }

        DefaultTexture = !DefaultTexture;
    }

    //Retorna o Speed de 0 a 1
    public float SetDirection(Vector3 MousePosition, Transform Arrow)
    {
        Arrow.position = transform.position;

        if (MousePosition == Vector3.zero) return 0;

        float Raio = Vector3.Distance(transform.position, MousePosition);
        if (Raio > 0.5f) Raio = 0.5f;
        if (Raio < 0.05f) return 0;

        Arrow.localScale = new Vector3(Raio * 5.0f, Arrow.localScale.y, Arrow.localScale.z);

        MousePosition[1] = transform.position.y;
        transform.LookAt(MousePosition);
        Arrow.LookAt(MousePosition);
        Arrow.Rotate(Arrow.up, 90);

        return Raio * 2.0f; //0 a 1f
    }

    bool Forced = false;
    public bool PerformMovement(int DiceNumber, float Speed) //Quando chegar retorna true
    {
        if (DiceNumber == 0) return false;

        if (!Forced)
            rigidbody.AddForce(transform.forward * Speed * (300f - (180f - ((float)(DiceNumber) * 30f))), ForceMode.Acceleration);
        Forced = true;

        if (rigidbody.IsSleeping() && rigidbody.velocity.magnitude == 0)
        {
            Forced = false;
            return true;
        }

        return false;
    }

    Transform PlayerHit = null;
    void OnCollisionEnter(Collision collision)
    {
        if ((collision.transform.tag == "PlayerA" || collision.transform.tag == "PlayerB") &&
            collision.transform.tag != transform.tag)
            PlayerHit = collision.transform;
    }

    Vector3 IniPos;
    public GameController.Event CheckFault(bool fstCheck, float Tolerancia = 0)
    {
        if (PlayerHit == null)
            return GameController.Event.NULL;
        if (fstCheck)
            IniPos = PlayerHit.position;
        else
        {
            Vector3 Delta = PlayerHit.position - IniPos;

            if (Delta.sqrMagnitude > Tolerancia * Tolerancia)
                return GameController.Event.Fault;
        }

        return GameController.Event.NULL;
    }
}